package com.t2c.tibetantochinese.common;

/**
 * Created by zoulu on 16/3/2.
 * http请求类
 */

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;
import com.t2c.tibetantochinese.MainApplication;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;


public class HttpRequest extends Request<String>{
    public static final String HEADER_KEY_TOKEN = "Authorization";
    public static final String HEADER_KEY_VERSION = "appver";
    public static final String HEADER_KEY_PLATFORM = "osver";

    protected static final String CHARSET = "utf-8";

    /** Content type for request. */
    private static final String PROTOCOL_CONTENT_TYPE =
            String.format("application/json; charset=%s", CHARSET);

    private static final Map<String, String> sHeaders = new HashMap<String, String>();


    private final String mRequestBody;
    protected static final String PROTOCOL_CHARSET = "utf-8";
    /**
     * 设置公共标准http header项
     * @param name 头项名称
     * @param value 头项值
     */
    public static void setCommonHeaderEntry(String name, String value){
        sHeaders.put(name, value);
    }

    private String mTag;
    private Listener<String> mListener;
    private StringBuilder mQueryString;

    public HttpRequest(int method, String url,String requestBody,
                          Listener<String> listener, ErrorListener errorListener) {
        super(method, url, errorListener);
        //设置请求超时
        this.setRetryPolicy(new DefaultRetryPolicy(9 * 1000, 1, 1.0f));
        mListener = listener;
        mRequestBody = requestBody;
    }


    @Override
    public String getUrl(){
        if(mQueryString == null){
            return super.getUrl();
        }else {
            return super.getUrl() + "?" + mQueryString.toString();
        }
    }

    //此处因为response返回值需要json数据,和JsonObjectRequest类一样即可
    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,HttpHeaderParser.parseCharset(response.headers));
            return Response.success(jsonString,HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        }
    }

    @Override
    protected void deliverResponse(String response) {
        if(mListener != null){
            mListener.onResponse(response);
        }
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError{
        return sHeaders;
    }



    @Override
    public byte[] getBody() throws AuthFailureError {
        try {
            return mRequestBody == null ? null : mRequestBody.getBytes(PROTOCOL_CHARSET);
        } catch (UnsupportedEncodingException uee) {
            VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
                    mRequestBody, PROTOCOL_CHARSET);
            return null;
        }
    }
    //设置内容类型，需要是application/json类型
    @Override
    public String getBodyContentType() {
        return PROTOCOL_CONTENT_TYPE;
    }

    /**
     * 提交请求
     */
    public HttpRequest commit(){
        MainApplication.getInstance().addToRequestQueue(this, mTag);
        return this;
    }

    /**
     * 提交请求
     */
    public void commit(Object tag){
        if(tag!=null) {
            MainApplication.getInstance().addToRequestQueue(this, tag);
        }else {
            MainApplication.getInstance().addToRequestQueue(this, mTag);
        }
    }

}

